package com.pan.server.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pan.pojo.dto.BookAddDTO;
import com.pan.pojo.dto.BookDTO;
import com.pan.pojo.entity.Book;
import com.pan.pojo.vo.BookVO;
import com.pan.server.mapper.BookMapper;
import com.pan.server.mapper.OrdersMapper;
import com.pan.server.service.BooksService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class BooksServiceImpl implements BooksService {

    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private OrdersMapper ordersMapper;

    @Override
    public PageInfo<BookVO> queryBooks(Integer pageNum, Integer pageSize) {

        PageHelper.startPage(pageNum, pageSize);

        List<BookVO> list = bookMapper.queryBooks();
        PageInfo<BookVO> pageInfo = new PageInfo<>(list);

        return pageInfo;
    }

    @Override
    public PageInfo<BookVO> searchBooks(BookDTO bookDTO, Integer pageNum, Integer pageSize) {

        PageHelper.startPage(pageNum, pageSize);
        List<BookVO> list = bookMapper.searchBooks(bookDTO);
        PageInfo<BookVO> pageInfo = new PageInfo<>(list);

        return pageInfo;
    }

    /**
     *
     * @param bookAddDTO
     */
    @Override
    public void addBook(BookAddDTO bookAddDTO) {

        Book book = Book.builder()
                .title(bookAddDTO.getTitle())
                .author(bookAddDTO.getAuthor())
                .publisher(bookAddDTO.getPublisher())
                .publishDate(new Date())
                .category(bookAddDTO.getCategory())
                .description(bookAddDTO.getDescription())
                .price(bookAddDTO.getPrice())
                .stock(bookAddDTO.getStock())
                .build();

        bookMapper.addBook(book);
        log.info("添加书籍成功");
    }

    @Override
    public void deleteBook(Integer id) {
        log.info("删除书籍...", id);

        List<Integer> orderId =ordersMapper.queryOrdersDetailByBookId(id);
        for (Integer integer : orderId) {
            ordersMapper.deleteOrderDetail(integer);
        }
        for (Integer integer : orderId) {
            ordersMapper.deleteOrder(integer);
        }


        bookMapper.deleteBook(id);

    }

    @Override
    public void updateBook(Book book) {


        bookMapper.updateBook(book);
    }
}